package org.clxmm.security03springboot.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author clxmm
 * @Description
 * @create 2021-06-07 8:45 下午
 */
@RestController
public class LoginController {


    @RequestMapping(value = "/login‐success")
    public String loginSuccess() {
        return " success login";
    }


    /**
     * 测试资源1 * @return
     */
    @GetMapping(value = "/r/r1")
    // 拥有p1权限才可以访问
    @PreAuthorize("hasAnyAuthority('p1')")
//    @PreAuthorize("hasAnyAuthority('p1','p3')")
    public String r1() {

        String username = getUsername();
        System.out.println(username);


        return " resource 1";
    }
    // 获取会话的上下文
    private String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(!authentication.isAuthenticated()){
            return null;
        }


        Object principal = authentication.getPrincipal();
        String username = null;
        if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
            username =    ((org.springframework.security.core.userdetails.UserDetails)principal).getUsername();
        } else {
            username = principal.toString();
        }

        return username;
    }


    /**
     * 测试资源2 * @return
     */
    @GetMapping(value = "/r/r2")
    public String r2() {
        return " resource 2";
    }

}
